package com.sixmac.common.base;

import com.sixmac.core.base.controller.BladeController;
import com.sixmac.core.constant.ConstCache;
import com.sixmac.core.constant.ConstCacheKey;
import com.sixmac.core.constant.ConstCurd;
import com.sixmac.core.toolbox.kit.StrKit;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * 用于拓展controller类
 */
public class BaseController extends BladeController implements ConstCurd, ConstCache, ConstCacheKey {

    /**
     * 获取登录用户的IP
     *
     * @throws Exception
     */
    protected String getRemortIP() {
        String ip = "";
        if (getRequest().getHeader("x-forwarded-for") == null) {
            ip = getRequest().getRemoteAddr();
        } else {
            ip = getRequest().getHeader("x-forwarded-for");
        }
        return ip;
    }

    public HashMap<String, Object> getData(String key, Object val) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put(key, val);
        return map;
    }

    public String getParameter(String name, String defaultValue) {
        String result = getRequest().getParameter(name);
        return StrKit.notBlank(result) ? result : defaultValue;
    }

    @InitBinder
    protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }
}
